package jp.sourceforge.akjrcp.psp.commands;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.akjrcp.flvtools.explorer.ThumbnailManager;
import jp.sourceforge.akjrcp.psp.PSPIOCommand;
import jp.sourceforge.akjrcp.psp.PSPSyncView;
import jp.sourceforge.akjrcp.util.FileCopy;
import jp.sourceforge.akjrcp.util.FileNameUtils;
import jp.sourceforge.akjrcp.util.image.ImageUtils;

import org.apache.commons.io.FileUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;

public class PSPCopyCommand extends AbstractIOCommand{
	FileCopy fileCopy;
	public PSPCopyCommand(File src,File dest,boolean overwrite){
		setSrcFile(src);
		setDestFile(dest);
		setOverwrite(overwrite);
	}
	
	public void setCanceld(boolean canceld) {
		super.setCanceld(canceld);
		if(fileCopy!=null){
			fileCopy.setCanceling(canceld);
		}
	}
	
	public int execCommand() {
		int ret=0;
		if(!getSrcFile().exists()){
			ret= PSPIOCommand.SRC_NOT_FOUND;
		}
		try {
			if(!canWrite(getDestFile())){
				
				ret= PSPIOCommand.DEST_CANT_WRITE;
				return ret;
			}
			fileCopy=new FileCopy(getSrcFile(), getDestFile());
			int result=fileCopy.exec();
			if(result!=0){
				//faild
				if(getDestFile().exists()){
					getDestFile().delete();//remove dest;
				}
				ret= PSPIOCommand.CANCELED;
				return ret;
			}else{
				PSPSyncView.log.info("copied-movie");
			}
			
			//FileUtils.copyFile(getSrcFile(), getDestFile());
			
		} catch (IOException e) {
			
			e.printStackTrace();
			ret= PSPIOCommand.DEST_CANT_WRITE;
			return ret;
		}
		

		//do thumb
		File imgFile=toPSPThumbnailFile(new File(FileNameUtils.getChangedExtensionName(getSrcFile(), "jpg",true)));
		if(imgFile!=null){
			File newFile=new File(FileNameUtils.getChangedExtensionName(getDestFile(), "jpg",true));
			try {
				FileUtils.copyFile(imgFile, newFile);
				PSPSyncView.log.info("copied-image");
			} catch (IOException e) {
				PSPSyncView.log.warn("image copy faild:"+imgFile);	
				e.printStackTrace();
			}
		}
		
		return ret;//ok
	}
	
	public String toString(){
		String label;
		if(isOverwrite()){
			label="Copy_Overwrite:"+getSrcFile()+","+getDestFile();
		}else{
			label="Copy:"+getSrcFile()+","+getDestFile();
		}
		return label;
	}

}
